package dbutilsDemo.jorm;

import java.sql.Connection;
import java.util.Properties;

import javax.sql.DataSource;

import org.javaclub.jorm.JormException;
import org.javaclub.jorm.common.Strings;
import org.javaclub.jorm.jdbc.DBUtil;
import org.javaclub.jorm.jdbc.JdbcException;
import org.javaclub.jorm.jdbc.connection.DBConnection;

import com.alibaba.druid.pool.DruidDataSourceFactory;

public class DruidDBConnection extends DBConnection {
	private DataSource ds;
	private Properties jdbcProperties;

	@Override
	public Connection getConnection() throws JdbcException {
		try {
			return ds.getConnection();
		} catch (Exception e) {
			e.printStackTrace();
			LOG.error("getConnection()", e);
			throw new JdbcException(e);
		}
	}


	@Override
	public void init() throws JormException {
		try {
			Properties p = new Properties();
			p.setProperty("driverClassName",
					getJdbcProperties().getProperty("connection.driver"));
			p.setProperty("url",
					getJdbcProperties().getProperty("connection.jdbcurl"));
			p.setProperty("username",
					getJdbcProperties().getProperty("connection.username"));
			p.setProperty("password",
					getJdbcProperties().getProperty("connection.password"));

			String poolMinSize = "1";
			String poolMaxSize = "28";
			try {
				poolMinSize = getJdbcProperties().getProperty(
						"connection.pool.min");
			} catch (Exception e) {
				poolMinSize = "1";
			}
			try {
				poolMaxSize = getJdbcProperties().getProperty(
						"connection.pool.max");
			} catch (Exception e) {
				poolMaxSize = "28";
			}
			p.setProperty("initialSize", poolMinSize);
			p.setProperty("maxActive", poolMaxSize);

			p.setProperty("maxIdle", "10");
			p.setProperty("maxWait", "30000");
			String testSql = getJdbcProperties().getProperty(
					"connection.test.sql");
			if (!Strings.isEmpty(testSql)) {
				p.setProperty("validationQuery", testSql);
				p.setProperty("testOnBorrow", "true");
			}
			ds = DruidDataSourceFactory.createDataSource(p);
		} catch (Exception e) {
			e.printStackTrace();
			try {
				throw new Exception(e);
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		} finally {

		}

	}

	@Override
	public boolean isOriginalConfigurationUsed() {
		String val = getJdbcProperties().getProperty("connection.pool.druid");
		return Strings.isNotEmpty(val);

	}

	@Override
	public void realReleaseAllConnections() throws JdbcException {
		DBConnection.getConnectionCache().remove(
				getJdbcProperties().getProperty("connection.provider.name"));
	}

	@Override
	public void releaseConnection(Connection conn) {
		if (null == conn) {
			return;
		}
		DBUtil.closeQuietly(conn);
	}

	@Override
	public Properties getJdbcProperties() {
		return this.jdbcProperties;
	}

	@Override
	public void setJdbcProperties(Properties jdbcProperties) {
		this.jdbcProperties = jdbcProperties;
	}
}
